package com.adamrocker.android.gorilla.util;

import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class Web {
	private static DefaultHttpClient sClient = new DefaultHttpClient();
	private static HttpGet sGetMethod = new HttpGet();
	
	public static InputStream getHttpInputStream(String url) throws IOException {
		try {
			sGetMethod.setURI(new URI(url));
		} catch (URISyntaxException e) {
			e.printStackTrace();
			return null;
		}

		HttpResponse response;
		try {
			response = sClient.execute(sGetMethod);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			throw new IOException("ProtocolException");
		}
		if (response.getStatusLine().getStatusCode() < 400) {
			try {
				return response.getEntity().getContent();//ここでOKのはず
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			throw new IOException("Connection Error("
					+ response.getStatusLine().getStatusCode());
		}
		throw new IOException("Unknown Web Error");
	}
	
	public static Bitmap getHttpBitmap(String url) throws IOException {
	    InputStream is = getHttpInputStream(url);
	    return BitmapFactory.decodeStream(is);
	}
}
